<script lang="ts" setup>
import {ref} from "vue";
import {onLoad, onPageScroll, onPullDownRefresh, onReachBottom} from "@dcloudio/uni-app";
import {useUserStore} from "@/stores/user";
import type {UserHomepageData} from "@/types/user";
import {getUserHomeDataApi, getUserHomeUploadApi, handleUserFollowApi} from "@/api/user";
import type {AnimalPreItem} from "@/types/animals";
import {UserHomeMenuType} from "@/enum/userHomeMenuType";

onPullDownRefresh(async () => {
  isNoMore.value = false
  page.value = 1
  uploadList.value = []
  if (!isRefreshUpload.value) {
    // 不为刷新upload时再获取
    await getUserHomeData()
  }
  await getUserUploadList()
  uni.stopPullDownRefresh()
})
onLoad(async (option) => {
  if (option) {
    type.value = Number(option.type) as 0 | 1
    userId.value = Number(option.userId)
  }
  // 获取用户主页数据
  await getUserHomeData()
  await getUserUploadList()
})
onReachBottom(async () => {
  page.value++
  await getUserUploadList()
})
const {safeAreaInsets} = uni.getSystemInfoSync()
const userHomeImg = ref()
const opacity = ref(0)
const type = ref<0 | 1>(0) //  0为用户主页，1为他人主页
const userId = ref<number>()
const loading = ref(false)
// 滑动到一定距离修改顶部导航的透明度
onPageScroll((e) => {
  e.scrollTop >= 240 ? opacity.value = 1 : opacity.value = 0
})
const userStore = useUserStore()
const goBack = () => {
  uni.navigateBack()
}
const goEdit = () => {
  uni.navigateTo({url: '/subPkg/profile/profile'})
}

// 获取用户信息
const page = ref(1)
const pageSize = ref(10)
const userHomeData = ref<UserHomepageData>()
const uploadList = ref<AnimalPreItem[]>([])
const isNoMore = ref(false)
const getUserHomeData = async () => {
  const res = await getUserHomeDataApi(userId.value!, type.value)
  userHomeData.value = res.data
}
const getUserUploadList = async () => {
  if (isNoMore.value) return
  loading.value = true
  const res = await getUserHomeUploadApi(page.value, pageSize.value, userId.value!, type.value, currentIndex.value)
  loading.value = false
  if (res.data.page * res.data.pageSize >= res.data.total) {
    isNoMore.value = true
  }
  if (res.data.data === null) return
  uploadList.value = uploadList.value.length > 0
      ? [...uploadList.value, ...res.data.data]
      : [...res.data.data]
}

// 处理点击关注
// 节流
const followDelay = ref(false)
const handleFollow = async () => {
  if (followDelay.value) return
  followDelay.value = true
  await handleUserFollowApi(userId.value!, userHomeData.value!.followType)
  await getUserHomeData()
  if (userHomeData.value!.followType === 1) {
    uni.showToast({title: '关注成功(≧∇≦)ﾉ', icon: 'none', duration: 1500})
  } else if (userHomeData.value!.followType === 3) {
    uni.showToast({title: '已互关', icon: 'none', duration: 1500})
  }
  followDelay.value = false
}
const handleUpdateFollow = async () => {
  if (userHomeData.value?.followType === 1 || userHomeData.value?.followType === 3) {
    // 当前是关注状态点击，执行取关
    uni.showActionSheet({
      itemList: ['取消关注'],
      itemColor: '#39c5bb',
      success: async (res) => {
        if (res.tapIndex === 0) {
          await handleFollow()
          await uni.showToast({title: '已取消关注', icon: 'none', duration: 1500})
        }
      }
    })
  }
}
// 点击前往粉丝或关注列表
const homeMenuType = UserHomeMenuType
const goFollowList = (type: 0 | 1 | 2) => {
  uni.navigateTo({url: '/subPkg/FollowAndFansList/FollowAndFansList?type=' + type + '&userId=' + userId.value})
}
const likePopup = ref()
const goChat = () => {
  uni.navigateTo({
    url: '/subPkg/chat/chat?receiverId=' + userId.value + '&receiverName=' + userHomeData.value!.user.username + '&receiverAvatar=' + userHomeData.value!.user.avatarURL
  })
}

// 点击头像预览
const onClickAvatar = () => {
  uni.previewImage({urls: [userHomeData.value!.user.avatarURL]})
}

const list = [{
  name: '图文'
}, {
  name: '图集',
}]

interface tabChange {
  index: 0 | 1
  name: string
}

const currentIndex = ref<0 | 1>(0) // 当前获取的upload类型
const isRefreshUpload = ref(false) // 当前刷新是否为upload
/**
 *  切换tab
 * @param e
 */
const onChange = (e: tabChange) => {
  currentIndex.value = e.index
  isRefreshUpload.value = true
  uni.startPullDownRefresh({
    complete: () => {
      isRefreshUpload.value = false
    }
  })
  // getUserUploadList()
}
</script>

<template>
  <scroll-view :scroll-y="true" class="user-home-box">
    <!--  顶部导航  -->
    <view :style="{ paddingTop: safeAreaInsets?.top + 'px' }" class="flex align-center justify-between"
          style="width: 100%;min-height: 60px;position: fixed;z-index: 999;transition: all .5s ease-in-out;padding-bottom: 20px">

      <view :style="{ opacity: opacity, paddingTop: safeAreaInsets?.top + 'px' }"
            class="flex justify-center align-center"
            style="transition: all .5s ease-in-out;position: absolute;z-index: -1;background: #FFFFFF;top: 0;left: 0;width: 100%;height: 80%">
        <text style="font-size: 18px;font-weight: 500">{{ userHomeData?.user.username }}</text>
      </view>


      <view class="justify-start " style="flex: 1;padding-left: 10px">
        <view class="btn cuIcon-back" @tap="goBack">
        </view>
      </view>
      <view class="justify-end align-center flex" style="flex: 2;gap: 10px;padding-right: 10px">
        <view v-if="type === 1" class=" btn cuIcon-mark" @click="goChat">
        </view>
        <view class="btn cuIcon-share">
        </view>
      </view>
    </view>
    <!--  背景图  -->
    <view ref="userHomeImg" class="user-home-img" style="width: 100%;height: 180px;position: relative">
      <view style="position:absolute;top: 0;left: 0;bottom: 0;right: 0;backdrop-filter: blur(15px);z-index: 1"></view>
      <uv-image :src="userHomeData?.user.avatarURL" height="100%" mode="aspectFill" width="100%"></uv-image>
    </view>
    <!--  主体内容  -->
    <view class="flex justify-end align-center" style="width: 100%;position: relative;">
      <!--    头像  -->
      <view style="position: absolute;top: 0;left: 70px;transform: translate(-50%,-25%);overflow: hidden;
      background: #e6e6e6;border-radius: 50%;width: 84px;height: 84px;z-index: 2;border: #FFFFFF 2px solid">
        <uv-image :src="userHomeData?.user.avatarURL" height="100%" radius="25px" width="100%" @click="onClickAvatar">
          <template v-slot:loading>
            <view class="flex flex-column justify-center align-center padding-bottom-sm"
                  style="width: 100%;height:100%;overflow: hidden">
              <uv-image :src="'/static/kun.png'" height="100%" mode="aspectFit" radius="50%" width="100%"></uv-image>
              <!--              <text v-if="userHomeData?.user.avatarURL" class="text-gray text-sm flex justify-center align-center " style="">图片暂缺</text>-->
            </view>
          </template>
          <template v-slot:error>
            <view class="flex flex-column justify-center align-center padding-bottom-sm"
                  style="width: 100%;height:100%;overflow: hidden">
              <uv-image :src="'/static/kun.png'" height="100%" mode="aspectFit" radius="50%" width="100%"></uv-image>
              <!--              <text v-if="false" class="text-gray text-sm flex justify-center align-center " style="">图片暂缺</text>-->
            </view>
          </template>
        </uv-image>
      </view>
      <!--    数据展示  -->
      <view class=" flex justify-center align-center flex-column" style="width: 200px;gap: 10px;margin: 0 10px 0 0">
        <view class="flex justify-center align-center " style="gap: 20px;padding: 5px 5px 0 0">
          <view class="flex flex-column justify-center align-center " style="gap: 5px"
                @click="goFollowList(homeMenuType.FANS)">
            <text class="text-black text-lg">{{ userHomeData?.fansCount }}</text>
            <text class="text-gray text-sm">粉丝</text>
          </view>
          <view class="bg-gray" style="width: 2px;height:20px "></view>
          <view class="flex flex-column justify-center align-center" style="gap: 5px"
                @click="goFollowList(homeMenuType.FOLLOW)">
            <text class="text-black text-lg">{{ userHomeData?.followCount }}</text>
            <text class="text-gray text-sm">关注</text>
          </view>
          <view class="bg-gray" style="width: 2px;height:20px "></view>
          <view class="flex flex-column justify-center align-center" style="gap: 5px" @click="likePopup.open()">
            <text class="text-black text-lg">{{ userHomeData?.likeCount }}</text>
            <text class="text-gray text-sm">获赞</text>
          </view>
        </view>
        <view v-if="type === 0" class="cu-tag radius line-awGreen flex align-center "
              style="width: 100%;height: 30px;font-size: 14px;border-width: 5px" @click="goEdit">
          <view class="flex align-center">编辑资料
            <text class="cuIcon-edit" style="font-size: 16px"></text>
          </view>
        </view>
        <view v-else-if="userHomeData?.followType === 0" class="cu-tag radius bg-gradual-awGreen flex align-center"
              style="gap: 3px;width: 100%;height: 30px;font-size: 14px;border-width: 2px" @click="handleFollow">
          <view class="flex align-center">
            <text class="cuIcon-add" style="font-size: 18px"></text>
            添加好友
          </view>
        </view>
        <view v-else-if="userHomeData?.followType === 1" class="cu-tag radius flex align-center bg-aw-gray"
              style="gap: 3px;width: 100%;height: 30px;font-size: 14px;border-width: 2px; " @click="handleUpdateFollow">
          <view class="flex align-center" style="gap: 5px">已关注
            <text class="cuIcon-check" style="font-size: 18px"></text>
          </view>
        </view>
        <view v-else-if="userHomeData?.followType === 2" class="flex flex-column align-center" style="width: 100%">
          <view class="cu-tag radius bg-gradual-awGreen flex align-center"
                style="gap: 3px;width: 100%;height: 30px;font-size: 14px;border-width: 2px" @click="handleFollow">
            <view class="flex align-center" style="gap: 2px">
              回关
            </view>
          </view>
          <text class="text-gray" style="font-size: 11px;padding-top: 3px">该用户关注了你哟~
          </text>
        </view>
        <view v-else-if="userHomeData?.followType === 3" class="cu-tag radius bg-aw-gray flex align-center"
              style="gap: 3px;width: 100%;height: 30px;font-size: 14px;border-width: 2px" @click="handleUpdateFollow">
          <view class="flex align-center" style="gap: 5px">已互关
            <text class="cuIcon-check" style="font-size: 18px"></text>
          </view>
        </view>
      </view>
    </view>
    <!-- 用户名及其他-->
    <view class="flex flex-column"
          style="width: 100%;gap: 10px;padding:5px 0 20px 20px;border-bottom: #e6e6e6 1px solid">
      <view class="flex align-center " style="gap: 10px">
        <text class="text-lg" style="align-self: flex-start;max-width: 150px">{{
            userHomeData?.user.username
          }}
        </text>
        <view :class="['cu-tag', 'text-white', 'round', uploadList.length >= 10 ? 'bg-gradual-awGreen' : 'bg-talent']"
              style="width: 45px;height: 18px;font-size: 10px">
          萌创达人
        </view>
      </view>
      <view class="text-gray text-sm">{{ userHomeData?.user.individualResume }}</view>
    </view>
    <!--  底部区域  -->
    <view style="width: 100%;padding: 0px 15px  0 15px;height: 100%">
      <uv-tabs
          :activeStyle="{
			color: '#303133',
			fontWeight: 'bold',
			transform: 'scale(1.08)'
    	}"
          :current="currentIndex"
          :inactiveStyle="{
		        color: '#606266',
			      transform: 'scale(1)'
		          }"
          :lineColor="'#39c5bb'"
          :list="list"
          itemStyle="padding-left: 15px; padding-right: 15px; height: 42px;"
          lineWidth="30"
          @click="onChange"></uv-tabs>
      <view class="text-gray text-sm">{{ type === 0 ? '我的上传' : 'ta的上传' }}
        <text style="padding-left: 5px;color: #3ebed3">{{ uploadList?.length }}</text>
      </view>
      <view v-if="uploadList?.length > 0" class="flex flex-wrap justify-between margin-top-sm"
            style="width: 100%;height: 100%;gap: 10px;row-gap: 10px">
        <view v-for="item in uploadList" :key="item.animalId" class="flex" style="width: 48%;height:200px">
          <aw-animal-item :upload-item="item"></aw-animal-item>
        </view>
        <view class="text-gray flex justify-center align-center" style="width: 100%">没有更多了哟~</view>
      </view>
      <view v-if="loading" style="width: 100%">
        <aw-loader></aw-loader>
      </view>
      <view v-else-if="!loading && uploadList?.length === 0"
            class="flex justify-center align-center padding-top-lg flex-column" style="width: 100%">
        <uv-image height="300px" src="/static/empty-data.png" width="300px"></uv-image>
        <text class="text-gray text-sm">这里什么都没有哟~</text>
      </view>
    </view>
  </scroll-view>


  <uni-popup ref="likePopup" type="dialog">
    <view class="bg-white padding-sm padding-top-lg flex flex-column"
          style="width: 300px;height: 180px;border-radius: 10px;overflow: hidden">
      <view class="text-gray flex-column flex align-center"
            style="width: 100%;flex:5;gap: 15px;border-bottom: #e6e6e6 1px solid">
        <text class="text-black text-xl">{{ userHomeData?.user.username }}</text>
        <text class="text-sm">评论、上传累计获赞</text>
        <text class="text-awGreen text-xxl">{{ userHomeData?.likeCount }}</text>
      </view>
      <view class="text-gray flex justify-center align-center padding-top-sm" style="width: 100%;flex: 1"
            @click="likePopup.close()">知道了
      </view>
    </view>

  </uni-popup>
</template>

<style lang="scss" scoped>
page {
  background: #FFFFFF;
}

.bg-talent {
  background: #ccc;
}

.user-home-box {
  width: 100%;
  background: #FFFFFF;
  min-height: 100vh;
  padding-bottom: 20px;
}

.btn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 32px;
  width: 32px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  font-size: 21px;
  color: #FFFFFF;
}
</style>
